package com.doubao.auth.controller;

import com.doubao.auth.dto.*;
import com.doubao.auth.service.AuthService;
import com.doubao.auth.service.PhoneAuthService;
import com.doubao.auth.service.VerificationCodeService;
import com.doubao.auth.service.WxAuthService;
import com.doubao.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Tag(name = "认证管理", description = "认证管理相关接口")
public class AuthController {

    private final AuthService authService;
    private final WxAuthService wxAuthService;
    private final VerificationCodeService verificationCodeService;
    private final PhoneAuthService phoneAuthService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "新用户注册")
    public Result<Void> register(@Valid @RequestBody RegisterRequest registerRequest) {
        return authService.register(registerRequest);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户名密码登录")
    public Result<JwtAuthResponse> login(@Valid @RequestBody LoginRequest loginRequest,
                                         HttpServletRequest request) {
        loginRequest.setIp(getClientIp(request));
        return authService.login(loginRequest);
    }

    /**
     * 微信小程序登录
     */
    @PostMapping("/wx-login")
    @Operation(summary = "微信小程序登录", description = "通过微信小程序登录")
    public Result<JwtAuthResponse> wxLogin(@Valid @RequestBody WxLoginRequest request) {
        return wxAuthService.wxLogin(request);
    }

    /**
     * 刷新令牌
     */
    @PostMapping("/refresh-token")
    @Operation(summary = "刷新令牌", description = "使用刷新令牌获取新的访问令牌")
    public Result<JwtAuthResponse> refreshToken(@Valid @RequestBody RefreshTokenRequest refreshTokenRequest) {
        return authService.refreshToken(refreshTokenRequest);
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    @Operation(summary = "退出登录", description = "用户退出登录")
    public Result<Void> logout(@RequestHeader("Authorization") String token) {
        return authService.logout(token);
    }

    /**
     * 发送短信验证码
     */
    @PostMapping("/send-code")
    @Operation(summary = "发送短信验证码", description = "发送短信验证码")
    public Result<Void> sendVerificationCode(@Valid @RequestBody SendCodeRequest request) {
        boolean sent = verificationCodeService.sendCode(request.getPhoneNumber());
        return sent ? Result.success() : Result.failed("验证码发送失败");
    }

    /**
     * 手机号验证码登录
     */
    @PostMapping("/phone-login")
    @Operation(summary = "手机号验证码登录", description = "使用手机号和验证码登录")
    public Result<JwtAuthResponse> phoneLogin(@Valid @RequestBody PhoneLoginRequest request,
                                              HttpServletRequest httpRequest) {
        request.setIp(getClientIp(httpRequest));
        return phoneAuthService.loginByPhone(request);
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 多个代理的情况，第一个IP为客户端真实IP
        if (ip != null && ip.indexOf(",") > 0) {
            ip = ip.substring(0, ip.indexOf(",")).trim();
        }
        return ip;
    }
}